import json
from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, filters
from rest_framework.exceptions import ValidationError

from apps.backend import models
from .serializers import PageNumberPagination, RoleModelSerializer, RoleAllSerializer
from drf_template_admin.services.RedisService import redis_connection

class RolesAllView(APIView):
    def get(self, request, *args, **kwargs):
        queryset = models.Roles.objects.filter(is_active=1).all().order_by("id")
        list = RoleAllSerializer(instance=queryset, many=True)
        return Response({'status': status.HTTP_200_OK, "data": list.data, 'message': 'success'})

class RolesView(GenericAPIView):
    queryset = models.Roles.objects.all().order_by("-id")
    serializer_class = RoleModelSerializer 
    pagination_class = PageNumberPagination
    filter_backends = [filters.SearchFilter, ] 
    search_fields = ["role_name", "is_active"] 

    def get(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            list = self.get_serializer(instance=page, many=True)
            result = self.get_paginated_response(list.data)
            return Response({'status': status.HTTP_200_OK, "data": result, 'message': 'success'})
        
        list = self.get_serializer(instance=queryset, many=True)


    def post(self, request, *args, **kwargs):
        redisConnection = redis_connection('token') 
        redis_token = json.loads(redisConnection.get_redis(request.auth))
        request.data['user_id'] = redis_token['id']
        ser = RoleModelSerializer(data=request.data) 
        if not ser.is_valid():
            raise ValidationError({'status': status.HTTP_428_PRECONDITION_REQUIRED, "errorCode": "30001", "errorMessage": ser.errors})
        
        ser.save()
        return Response({'status': status.HTTP_201_CREATED, 'data': [], "message": "success"})
    
class RolesDetailView(APIView):
    def put(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        try:
            queryset = models.Roles.objects.get(id=pk)
        except models.Roles.DoesNotExist:
            raise ValidationError({"status": status.HTTP_400_BAD_REQUEST, "errorCode": "30002", "errorMessage": '数据不存在'})
        
        ser = RoleModelSerializer(instance=queryset, data=request.data)
        if not ser.is_valid():
            return Response({'status': status.HTTP_428_PRECONDITION_REQUIRED, "errorCode": "30001", "errorMessage": ser.errors})
        
        ser.save()
        return Response({'status': status.HTTP_200_OK, "data":[], 'message': 'success'})  
    
    def delete(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        
        try:
            queryset = models.Roles.objects.get(id=pk)
        except models.Roles.DoesNotExist:
            raise ValidationError({"status": status.HTTP_400_BAD_REQUEST, "errorCode": "30002", "errorMessage": '数据不存在'})
        
        queryset.is_active = True if queryset.is_active == False else False 
        message = "删除成功" if queryset.is_active == False else "恢复成功"
        queryset.save()  
        return Response({'status': status.HTTP_200_OK, "data": [], 'message': message})    
